<template>
	<view class="u-page">
		<view class="u-demo-block">
			<u--form
				labelPosition="left" 
				:labelWidth="80" 
				:model="formData" 
				:rules="formRules" 
				ref="form">
				<!-- 输入账户 -->
				<u-form-item
					label="账户号"
					required
					prop="userInfo.userCode"
					ref="userCode">
					<u-input
						v-model="formData.userInfo.userCode"
						clearable
						:disabled="disabled.userCode"
						:focus="focus.userCode"
						@focus="userCodeFocus"
						@blur="userCodeBlur()">
					</u-input>				
				</u-form-item>
				<view class="echo">
					<u--text
						type="success"
						:text="echo.userCode">
					</u--text>
				</view>
				<!-- 输入设备 -->
				<u-form-item
					label="设备号"
					required
					prop="machineInfo.machineNo"
					ref="machineNo">
					<u-input
						v-model="formData.machineInfo.machineNo"
						clearable
						:disabled="disabled.machineNo"
						:focus="focus.machineNo"
						@focus="machineNoFocus"
						@blur="machineNoBlur()">
					</u-input>				
				</u-form-item>
				<view class="echo">
					<u--text
						type="success"
						wordWrap="break-word"
						:lines="3"
						:text="echo.machineNo">
					</u--text>
				</view>
				<u-line :customStyle="{marginTop:'5px'}"></u-line>
				<!-- 记录的内容 -->
				<view v-show="show.otherRecordItem">
					<!-- 选择日期+值别 -->
					<u-form-item
						label="日期轮班"
						prop="recordTime"
						ref="recordTime"
						required
						@click="recordTimeClick">
						<u-input
							v-model="formData.recordTime"
							style="pointer-events: none"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择日期轮班"
							fontSize="13px"
							color="#12569F"
							suffixIcon="arrow-right">
						</u-input>
					</u-form-item>
					<!-- 计划产量 -->
					<u-form-item
						label="计划产量"
						ref="planOutput">
						<u-input
							v-model="formData.planOutput"
							type="number"
							placeholder="请输入计划产量"
							clearable>
							<u--text slot="suffix" type="info" text="kpcs"></u--text>
						</u-input>				
					</u-form-item>
					<!-- 实际产量 -->
					<u-form-item
						label="实际产量"
						required
						prop="actualOutput"
						ref="actualOutput">
						<u-input
							v-model="formData.actualOutput"
							type="number"
							placeholder="请输入实际产量"
							clearable>
							<u--text slot="suffix" type="info" text="kpcs"></u--text>
						</u-input>				
					</u-form-item>
					<!-- 计划产量 -->
					<u-form-item
						label="不良数"
						ref="defect">
						<u-input
							v-model="formData.defect"
							type="number"
							placeholder="请输入不良数"
							clearable>
							<u--text slot="suffix" type="info" text="pcs"></u--text>
						</u-input>				
					</u-form-item>
					<!-- 输入备注 -->
					<u-form-item
						label="备注"
						prop="remark"
						ref="remark">
						<u--textarea
							v-model="formData.recordRemark"
							placeholder="按需输入"
							autoHeight
							count
							:maxlength="144">
							
						</u--textarea>
					</u-form-item>
				</view>
			</u--form>
			<!-- 表格表示数据 -->
			<view v-show='show.table'>
				<uni-table border stripe emptyText="暂无更多数据" >
					<!-- 表头行 -->
					<uni-tr>
						<uni-th align="center">日期</uni-th>
						<uni-th align="center">产量</uni-th>
					</uni-tr>
					<!-- 表格数据行 -->
					<uni-tr v-for="(item,index) in tableDate" :key="index">
							<uni-td>{{item | tableDataFilter}}</uni-td>
							<uni-td>产量:{{item.actualOutput}} kpcs<br>不良:{{item.defect}} pcs</uni-td>
					</uni-tr>
<!-- 					<uni-tr>
						<uni-td>2020-10-20</uni-td>
						<uni-td>Jeson</uni-td>
						<uni-td>北京市海淀区</uni-td>
					</uni-tr>
 -->				
				</uni-table>
				
			</view>



			
			<!-- 按钮 -->
			<u-button
				type="primary"
				:text="submitBtn.text"
				customStyle="margin-top: 20px"
				:loading="submitBtn.loading"
				:disabled="submitBtn.disabled"
				loadingMode="semicircle"
				@click="formSubmit">
			</u-button>
			
			<u-button
				type="warning"
				text="重置"
				plain
				customStyle="margin-top: 20px"
				@click="formReset">
			</u-button>
			<!-- 日期轮班picker -->
			<u-picker 
				:show="show.dateShiftPicker" 
				:columns="pickerDataArr"
				closeOnClickOverlay
				:defaultIndex="pickerDefaultVal"
				@cancel="show.dateShiftPicker=false"
				@close="show.dateShiftPicker=false"
				@confirm="dateShiftPickerConfirm">
			</u-picker>

		</view>
		
	</view>
</template>

<script>
	import {getUserCodeEcho} from '@/api/user/user.js';
	import {getMachineNoEcho} from '@/api/machine/machine.js'
	import {getPlanOutput} from '@/api/planoutput/planoutput.js';
	import {getShiftCapaRecordTimeLine} from '@/api/shiftcaparecord/shiftcaparecord.js'
	
	import {insertShiftCapacityRecord} from '@/api/shiftcaparecord/shiftcaparecord.js'
	
	import xbctimer from '@/js_sdk/xbc-timer/timer-1.1.6.js'
	import dayjs from '@/uni_modules/uview-ui/libs/util/dayjs.js'
	
	export default {
		data() {
			return {
				// 表单数据
				formData:{
					userInfo:{
						userCode:''
					},
					machineInfo:{
						machineNo:''
					},
					recordTime:'',
					planOutput:0,
					actualOutput:null,
					defect:0,
					recordRemark:''
				},
				// 校验数据
				formRules:{
					'userInfo.userCode':[
						{
							type: 'string',
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change'],
						},
						{
							asyncValidator:(rule,value,callback)=>{
								if(uni.$u.test.isEmpty(value)){
									callback(new Error('不能为空'))
									return
								}
								getUserCodeEcho({userCode:value}).then(res=>{
									this.echo.userCode=res.data.departmentsPO.departmentName + '\n'+ res.data.usersPO.userFullName
									this.disabled.machineNo=false
									this.disabled.userCode=true
									
									uni.$u.sleep(300).then(()=>{
										this.focus.machineNo=true
										this.machineNoFocus()
									})
									callback()
								}).catch(err=>{
									callback(new Error(err.message|| err.msg || (err.errMsg+'; 服务器异常')))
								})
							},
							// trigger:['blur']
						}
					],
					'machineInfo.machineNo':[
						{
							type: 'string',
							required: true,
							message: '请填写设备号',
							trigger: ['blur', 'change']
						},
						{
							asyncValidator:(rule,value,callback)=>{
								if(uni.$u.test.isEmpty(value)){
									callback(new Error('不能为空'))
								}
								let params = {
									machineNo: value,
									userCode : this.formData.userInfo.userCode
								}
								getMachineNoEcho(params).then(res=>{
									uni.$u.sleep(50).then(()=>{
										// this.echo.machineNo=res.data.topDept.topDeptName+'\n' + res.data.secDept.secDeptName + '\n' + res.data.machine.machineName
										this.echo.machineNo=res.data
										this.disabled.machineNo=true
										this.show.otherRecordItem=true
									})
									callback()
								}).catch(err=>{
									callback(new Error(err.message|| err.msg || (err.errMsg+'; 服务器异常')))
								})
							},
						}
					
					],
					recordTime:[
						{
							type: 'string',
							required: true,
							message: '不能为空',
							trigger: ['blur', 'change'],
						},
					],
					planOutput:[
						{
							// 自定义验证函数，见上说明
						// 	validator: (rule, value, callback) => {
						// 		if(uni.$u.test.isEmpty(value)){
						// 			return false
						// 		}
						// 		if(Number(value)<0){
						// 			return false
						// 		}
						// 		return true;
						// 	},
						// 	message:'必填且≥0',
						// 	trigger:['change','blur']
						}
					],
					actualOutput:[
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								if(uni.$u.test.isEmpty(value)){
									return false
								}
								if(Number(value)<0){
									return false
								}
								return true;
							},
							message:'必填且≥0',
							trigger:['change','blur']
						}
					],
					defect:[
						{
							// 自定义验证函数，见上说明
						// 	validator: (rule, value, callback) => {
						// 		if(uni.$u.test.isEmpty(value)){
						// 			return false
						// 		}
						// 		if(Number(value)<0){
						// 			return false
						// 		}
						// 		return true;
						// 	},
						// 	message:'必填且≥0',
						// 	trigger:['change','blur']
						}
					]
				},
				// show
				show:{
					otherRecordItem:false,
					dateShiftPicker:false,
					table:false,
				},
				// 焦点
				focus:{
					userCode:false,
					machineNo:false,
				},
				// 禁用
				disabled:{
					userCode:false,
					machineNo:true,
				},
				// input回显
				echo:{
					userCode:'',
					machineNo:''
				},
				// 计时器
				timer:{
					userCode:0,
					machineNo:0
				},
				// 选时间用的 picker
				pickerDataArr:[
					['数据1','数据2'],
					['9点','11点','13点','15点','17点','19点','21点','23点','1点','3点','5点','7点']
				],
				pickerDefaultVal:[0,0],
				// 提交按钮的属性
				submitBtn:{
					text:'提交',
					loading:false,
					disabled:false
				},
				tableDate:[]
			};
		},
		onNavigationBarButtonTap(e) {
			if (e.type === 'menu') {
				this.showMenuDrawer();
			} else if (e.type === 'home') {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			}
		},
		onShow() {
			this.$nextTick(()=>{
				this.focus.userCode=true
			})

		},
		onUnload(){
			clearTimeout(this.timer.userCode)
			clearTimeout(this.timer.machineNo)
		},
		filters:{
			tableDataFilter(value){
				let recordTimeDT = value.recordTimeDT;
				// if(dayjs(recordTimeDT).hour()==20){
				// 	return uni.$u.timeFormat(recordTimeDT,'yyyy-mm-dd 1值')
				// }
				// if(dayjs(recordTimeDT).hour()==8){
				// 	return dayjs(recordTimeDT).add(-1,'day').format('YYYY-MM-DD 2值')
				// }
				return uni.$u.timeFormat(recordTimeDT,'yyyy-mm-dd hh点');
			}
		},
		methods:{

			userCodeFocus(){
				if(this.echo.userCode!=''){
					this.echo.userCode=''
				}
				this.$nextTick(()=>{
					// #ifdef APP-PLUS
					uni.hideKeyboard()
					// #endif
				})

			},
			machineNoFocus(){
				if(this.echo.machineNo!=''){
					this.echo.machineNo=''
				}
				this.$nextTick(()=>{
					// #ifdef APP-PLUS
					uni.hideKeyboard()
					// #endif
				})
			},
			userCodeBlur(){
				this.timer.userCode= setTimeout(()=>{
					this.$refs.form.validateField('userInfo.userCode');
				},666)
			},
			machineNoBlur(){
				this.timer.machineNo= setTimeout(()=>{
					this.$refs.form.validateField('machineInfo.machineNo');
				},666)				
			},
			recordTimeClick(){
				this.$refs.form.validateField('userInfo.userCode')
				this.$refs.form.validateField('machineInfo.machineNo')
		
				// 计算出前7天的日期,使用 js_sdk/xbc-timer
				// 值日期
				this.show.dateShiftPicker=true
				this.pickerDataArr[0].splice(0,this.pickerDataArr[0].length)
				xbctimer.getLatestDates(7,true).forEach(item=>{
						this.pickerDataArr[0].push(item)
				})
				// 默认2值
				// pickerDefaultVal默认 [0,0]
				let hh=new Date().getHours();
				// let mm=new Date().getMinutes();
				
				// console.log(this.pickerDataArr[0].length);
				
				if(hh>=9 && hh<11){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,0)
				}
				else if(hh>=11 && hh<13){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,1)
				}
				else if(hh>=13 && hh<15){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,2)
				}
				else if(hh>=15 && hh<17){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,3)					
				}
				else if(hh>=17 && hh<19){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,4)
				}
				else if(hh==19  && hh<21){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,5)
				}
				else if(hh>=21 && hh<23){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,6)
				}
				else if(hh>=23 || hh<1){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,7)
				}
				else if(hh>=1 && hh<3){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,8)
				}
				else if(hh>=3 && hh<5){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,9)
				}
				else if(hh>=5 && hh<7){
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,10)
				}
				else {
					this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
					this.pickerDefaultVal.splice(1,1,11)
				}
				
				//if(new Date().getHours()>=20 || new Date().getHours()<8 ){
				// 	// 修改第1位
				// 	this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-2)
				// 	// 修改第2位
				// 	this.pickerDefaultVal.splice(1,1,1)
				// } 
				// else{
				// 	this.pickerDefaultVal.splice(0,1,this.pickerDataArr[0].length-1)
				// 	this.pickerDefaultVal.splice(1,1,0)
				// }

			},
			dateShiftPickerConfirm(e){
				this.formData.recordTime=e.value.join(" ")
				this.show.dateShiftPicker=false
				this.show.table=false
				this.tableDate=[]
				this.formData.planOutput=null
				this.formData.actualOutput=null
				this.formData.defect=null
				let whatTimeStr=this.formData.recordTime.split(" ")[1]	//几点
				let beginDateStr=''
				let endDateStr=''
				
				// 1值,获取计划产量,填充1值的开始时间和结束时间
				if((whatTimeStr.split('点')[0])*1<=19 && (whatTimeStr.split('点')[0])*1>7){
					this.funcGetPlanOutput(this.formData.machineInfo.machineNo,1,whatTimeStr.split('点')[0])
					beginDateStr = this.formData.recordTime.split(" ")[0] + ' 07:00:00'
					endDateStr = dayjs(this.formData.recordTime).add(1,'day').format('YYYY-MM-DD')+' 07:00:00'
				}
				else {
					this.funcGetPlanOutput(this.formData.machineInfo.machineNo,2,whatTimeStr.split('点')[0])
					if((whatTimeStr.split('点')[0])*1>19){
						beginDateStr = this.formData.recordTime.split(" ")[0] + ' 07:00:00'
						endDateStr = dayjs(this.formData.recordTime).add(1,'day').format('YYYY-MM-DD')+' 07:00:00'
					}	else {
						beginDateStr = dayjs(this.formData.recordTime).add(-1,'day').format('YYYY-MM-DD')+' 07:00:00'
						endDateStr = this.formData.recordTime.split(" ")[0] + ' 07:00:00'
					}
				}
				getShiftCapaRecordTimeLine({
					machineNo:this.formData.machineInfo.machineNo,
					beginDate: beginDateStr,
					endDate:endDateStr
				})
				.then(res=>{
					this.show.table=true
					this.tableDate=res.data
				})
				.catch(err=>{
					if(uni.$u.test.isEmpty(err.msg)||uni.$u.test.isEmpty(err.msg)){
						uni.$u.toast('表格数据获取异常')
					}
				})
				
				return 
				
				
				
				// 获取每值的计划产量
				/*
				if(whatTimeStr.includes("1值")){
					this.funcGetPlanOutput(this.formData.machineInfo.machineNo,1,0)
					beginDateStr = this.formData.recordTime.split(" ")[0] + ' 08:00:00'
					endDateStr = dayjs(this.formData.recordTime).add(1,'day').format('YYYY-MM-DD')+' 08:00:00'
				} 
				else if(whatTimeStr.includes("2值")){
					this.funcGetPlanOutput(this.formData.machineInfo.machineNo,2,0)
					beginDateStr = this.formData.recordTime.split(" ")[0] + ' 08:00:00'
					endDateStr = dayjs(this.formData.recordTime).add(1,'day').format('YYYY-MM-DD')+' 08:00:00'
				} 
				else{
					if(whatTimeStr.split('点')[0]<20 && whatTimeStr.split('点')[0]>8){
						this.funcGetPlanOutput(this.formData.machineInfo.machineNo,1,whatTimeStr.split('点')[0])
						beginDateStr = this.formData.recordTime.split(" ")[0] + ' 08:00:00'
						endDateStr = dayjs(this.formData.recordTime).add(1,'day').format('YYYY-MM-DD')+' 08:00:00'
					}
					else {
						this.funcGetPlanOutput(this.formData.machineInfo.machineNo,2,whatTimeStr.split('点')[0])
						beginDateStr = dayjs(this.formData.recordTime).add(-1,'day').format('YYYY-MM-DD')+' 08:00:00'
						endDateStr = this.formData.recordTime.split(" ")[0] + ' 08:00:00'
					}
					getShiftCapaRecordTimeLine({
						machineNo:this.formData.machineInfo.machineNo,
						beginDate: beginDateStr,
						endDate:endDateStr
					})
					.then(res=>{
						this.show.table=true
						this.tableDate=res.data
					})
					.catch(err=>{
						uni.$u.toast(err.msg || err.message || '表格数据获取异常')
					})
				}
				*/
			},
			 
			/**
			 * 获取默认计划产量
			 * @param {Object} machineNo
			 * @param {Object} dayOrNight	1=1值,2=2值
			 * @param {Object} whatTime	0表示值产量,>0表示几点
			 */
			funcGetPlanOutput(machineNo,dayOrNight,whatTime){
				const _this= this;
				getPlanOutput({machineNo:machineNo,dayOrNight:dayOrNight}).then(res=>{
					_this.formData.planOutput=res.data.planOutput
					if(dayOrNight==1 && (whatTime!=0)){
						_this.formData.planOutput =	Math.round((whatTime*1-7)* (res.data.planOutput/12))
					}
					else if(dayOrNight==2 && (whatTime!=0))
					{
						if(whatTime<=7){
							_this.formData.planOutput =	Math.round((whatTime*1+24-7) * (res.data.planOutput/24))
						}else{
							_this.formData.planOutput =	Math.round((whatTime*1-7) * (res.data.planOutput/24))
						}
					}
					else {
						throw "时间计算异常"
					}
					
				}).catch(err=>{
					_this.formData.planOutput=0;
				})
			},
			formSubmit(){
				const _this= this;
				//数据验证
				this.$refs.form.validate()
					.then(res=>{
						uni.showModal({
							title:'上传',
							content:'确认数据上传?',
							success:(res)=>{
								if(res.confirm){
									// 每值的时间计算
									// 1值记作8点, 2值记作20点
									let tmpArr=_this.formData.recordTime.split(' ');
									let tmpTime=null;
									if(tmpArr.length!=2 || ((!_this.formData.recordTime.includes('点'))) ){
										uni.$u.toast('提交数据异常')
										return
									}
									
									if(_this.formData.recordTime.includes(' 9点')){
										tmpTime = _this.formData.recordTime.replace(' 9点',' 09:00:00')
									}
									else if(_this.formData.recordTime.includes('11点')){
										tmpTime = _this.formData.recordTime.replace('11点','11:00:00')
									}
									else if(_this.formData.recordTime.includes('13点')){
										tmpTime = _this.formData.recordTime.replace('13点','13:00:00')
									}
									else if(_this.formData.recordTime.includes('15点')){
										tmpTime = _this.formData.recordTime.replace('15点','15:00:00')
									}
									else if(_this.formData.recordTime.includes('17点')){
										tmpTime = _this.formData.recordTime.replace('17点','17:00:00')
									}
									else if(_this.formData.recordTime.includes('19点')){
										tmpTime = _this.formData.recordTime.replace('19点','19:00:00')
									}
									else if(_this.formData.recordTime.includes('21点')){
										tmpTime = _this.formData.recordTime.replace('21点','21:00:00')
									}
									else if(_this.formData.recordTime.includes('23点')){
										tmpTime = _this.formData.recordTime.replace('23点','23:00:00')
									}
									else if(_this.formData.recordTime.includes(' 1点')){
										tmpTime = _this.formData.recordTime.replace(' 1点',' 01:00:00')
									}
									else if(_this.formData.recordTime.includes(' 3点')){
										tmpTime = _this.formData.recordTime.replace(' 3点',' 03:00:00')
									}
									else if(_this.formData.recordTime.includes(' 5点')){
										tmpTime = _this.formData.recordTime.replace(' 5点',' 05:00:00')
									}
									else if(_this.formData.recordTime.includes(' 7点')){
										tmpTime = _this.formData.recordTime.replace(' 7点',' 07:00:00')
									}

									// if(tmpArr[1].includes('1')){
									// 	tmpTime=new Date(tmpArr[0]).getTime()
									// } else{
									// 	tmpTime=new Date(tmpArr[0]+' '+'20:00:00').getTime()
									// }
									// // 获取和计算时区的差,计算完的时间是东8区
									// let utcTimeOffset = new Date().getTimezoneOffset()
									// if(utcTimeOffset!=(-480)){
									// 	tmpTime=tmpTime+(utcTimeOffset-480)*60000
									// }
									
									let tmpdata={
										userCode: _this.formData.userInfo.userCode,
										machineNo:_this.formData.machineInfo.machineNo,
										recordTimeDT: tmpTime,
										planOutput:Number(_this.formData.planOutput),
										actualOutput:Number(_this.formData.actualOutput),
										defect:Number(_this.formData.defect),
										recordRemark:_this.formData.recordRemark
									}
									// 提交到服务端
									insertShiftCapacityRecord(tmpdata).then(res=>{
										uni.showToast({
											title:'提交成功',
											duration:2000,
										})
										// uni.$u.sleep(2000).then(()=>{
										// 	uni.reLaunch({
										// 			url:'/pages/index/index'
										// 	})
										// })
										_this.formData.recordTime=''
										_this.formData.planOutput=0
										_this.formData.actualOutput=null
										_this.formData.defect=0
										_this.formData.recordRemark=''
										_this.tableDate=[]
										_this.$refs.form.clearValidate()
										
									}).catch((err)=>{
										uni.showToast({
											title: err.msg||' 服务器异常',
											icon:'error',
											duration:2000,
										})
									}).finally(()=>{
										_this.submitBtn.text="提交"
										_this.submitBtn.disabled=false
										_this.submitBtn.loading=false
									})
								}
							}
						})
					})
					.catch(err=>{
						uni.showToast({
							title:'提交数据错误',
							icon:'error',
							duration:2000
						})
					})
			},
			formReset(){
				this.$refs.form.resetFields()
				this.echo.userCode=''
				this.echo.machineNo=''
				this.disabled.userCode=false
				this.disabled.machineNo=true
				this.show.otherRecordItem=false
				this.show.table=false
				this.$nextTick(()=>{
					this.focus.userCode=true
				})
			},
			
		}
	}
</script>

<style lang="scss">
.echo {
	margin-left: 80px;
}
</style>
